package com.term.appadmin.controller.common;

import com.term.appadmin.controller.BaseController;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * Created by chenGang on 2017/1/17.
 */
@Controller
public class CommonController extends BaseController {

    /**
     * 请求登录界面
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        Subject currentUser= SecurityUtils.getSubject();
        if (!currentUser.isAuthenticated()&&currentUser.isRemembered()){
            return "redirect:/home";
        }
        return "login";
    }

    /**
     * 验证登录信息
     * @param userName
     * @param password
     * @param rememberMe
     * @param model
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String fail(@RequestParam(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM) String userName, @RequestParam(FormAuthenticationFilter.DEFAULT_PASSWORD_PARAM) String password,
                       @RequestParam(FormAuthenticationFilter.DEFAULT_REMEMBER_ME_PARAM) String rememberMe, Model model) {
        UsernamePasswordToken token=new UsernamePasswordToken(userName,password);
        token.setRememberMe(Boolean.valueOf(rememberMe));
        Subject currentUser=SecurityUtils.getSubject();
        try {
            currentUser.login(token);
        }catch (AuthenticationException e){
            model.addAttribute("errorInfo","用户名或密码错误");
        }
        if (currentUser.isAuthenticated()||currentUser.isRemembered()){
            return "redirect:/home";
        }
        return "login";
    }

    /**
     * 首页
     * @return
     */
    @RequestMapping(value = "/home",method = RequestMethod.GET)
    public String home() {
        return "home";
    }

    /**
     * 注销
     * @return
     */
    @RequestMapping(value = "/logout")
    public String logout(){
        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()){
            currentUser.logout();
        }
        return "login";
    }

    @RequestMapping(value = "/welcome",method = RequestMethod.GET)
    public String welcome() {
        return "welcome";
    }

}
